<?php
error_reporting(E_ALL);
error_reporting(E_ALL^E_STRICT);
ini_set( "display_errors", 1 ) ;
ini_set( "default_charset", "UTF-8" ) ;

define( "ARROW_ABSOLUTE_PATH", dirname(__FILE__)."/server"); 
define( "ARROW_CORE_PATH", ARROW_ABSOLUTE_PATH."/core" );
define( "ARROW_CACHE_PATH", "./cache" );
define( "ARROW_MODELS_PATH", ARROW_ABSOLUTE_PATH."/standardModels" );
define( "ARROW_CONF_PATH", ARROW_ABSOLUTE_PATH."/conf" );
define( "ARROW_PROJECTS_PATH", "./projects" );
define( "ARROW_LOG_PATH", "./log" );

//if(isset($_SESSION["ARROW_SUPER_CACHE"]))
//  define( "SUPER_CACHE", $_SESSION["ARROW_SUPER_CACHE"] );
//else
define( "SUPER_CACHE", false );
define( "DEBUG_STATS", true );

if( DEBUG_STATS && isset($_GET["dev"]) ) {
  $db_start_time = microtime(true);
  $db_memory_init = number_format(memory_get_usage(1), 0, '.', ',') ;
}



date_default_timezone_set("Europe/Warsaw") ;

require_once(ARROW_CORE_PATH."/ArrowObject.php");
require_once(ARROW_CORE_PATH."/ArrowLogger.php");
require_once(ARROW_CORE_PATH."/ArrowException.php");
require_once(ARROW_CORE_PATH."/ArrowCoreException.php");
require_once(ARROW_CORE_PATH."/ArrowConfProvider.php");
require_once(ARROW_CORE_PATH."/ArrowCacheProvider.php");
require_once(ARROW_CORE_PATH."/ArrowController.php");

$includedModels = ArrowCacheProvider::importModelsCache();
ArrowController::setLoadedModels($includedModels);

require_once(ARROW_CORE_PATH."/ArrowRequestContext.php");
require_once(ARROW_CORE_PATH."/ArrowStateManager.php");
require_once(ARROW_CORE_PATH."/ArrowRouter.php");
require_once(ARROW_CORE_PATH."/ArrowTemplateParser.php");
require_once(ARROW_CORE_PATH."/ArrowView.php");

if( DEBUG_STATS && isset($_GET["dev"]) ) {
  require_once(ARROW_MODELS_PATH."/org/arrowplatform/orm/db/ArrowOrmMysql.php");
  ArrowOrmMysql::executionTime();
  ArrowController::importModel("auth.AccessManager");
  AccessManager::configMode();
}

ArrowLogger::log("[Main] Starting..");

ArrowRouter::$INDEX_FILE = basename( __FILE__ ) ;

$router = ArrowRouter::getDefault( ArrowRequestContext::getDefault());

$controler = ArrowController::getDefault( $router );

/*if( file_exists("./kits") && isset($_GET["rewrite_name"]) ) {
  echo "<div style=\"width:700px;margin:auto;text-align:center;background-color:#CCFF99;\" ><h2>Istnieje dostęp do katalogu z narzędziami (./kits) <br />Niebiezpieczne !!!<br /> Usuń go (zalecane) bądź zmień jego nazwę</h2></div>\n" ;
}*/

if( DEBUG_STATS && isset($_GET["dev"]) ) {
  $db_memory_after_init = number_format(memory_get_usage(1), 0, '.', ',') ;
}

if( ($mediator = $router->getMediator()) ){
  ArrowLogger::log("[Main] Mediator call checking...");
	
	if($mediator->getCheckResult(ArrowRequestContext::getDefault()) != true){
		
		ArrowLogger::log("[Main] Mediator returns false, must rollback request...", ArrowLogger::EL_INFO);
		
		if( $router->getCallType() == ArrowRouter::ACTION_BEAN_CALL || $router->getCallType() == ArrowRouter::TEMPLATE_CALL ){
			$controler->rollBackRequest();
		}elseif($router->getCallType() == ArrowRouter::REMOTE_CALL){
			ArrowLogger::log( "[Main] Remote mediator call, mediator returns false, returning error XML" );
			$remoteResponseHAndler = ArrowController::$activeProject->getHandler(ArrowProject::IRemoteResponseHandler);
			$remoteResponseHAndler->setHeaders();
			$response = $remoteResponseHAndler->getResponse(array( "error" => $mediator->getError() ));
			ArrowController::end($response);
		}
	}
	
	ArrowLogger::log( "[Main] Mediator returns true, executing request..." );
	
	//after check - static address
	$afterAddress = $mediator->getAfterAddress();
	
 	//after check go to view without mediator parametr
	if( $router->getCallType() == ArrowRouter::TEMPLATE_CALL){
		if( !empty($afterAddress) )
	    	$controler->redirectToStaticAddress($afterAddress);
		
		$controler->processToView();
	}

}

switch ( $router->getCallType() ){
	case ArrowRouter::ACTION_BEAN_CALL:
		$actionBean = $router->getActionBean();
		$instance = $actionBean->getBeanInstance();
		if( $instance instanceof IArrowBeanMediator  && $instance->getCheckResult(ArrowRequestContext::getDefault()) != true )
			$controler->rollBackRequest();	
		$controler->executeBean( $actionBean );
		
	    if( isset($afterAddress) && !empty($afterAddress) )
	    	$controler->redirectToStaticAddress($afterAddress);
	    	
		
		$controler->processToView();
	break;
	case ArrowRouter::REMOTE_CALL:
		$dataProviderBean = $router->getDataProviderBean();
		$instance = $dataProviderBean->getBeanInstance();
		if( $instance instanceof IArrowBeanMediator  && $instance->getCheckResult(ArrowRequestContext::getDefault()) != true ){
			$remoteResponseHAndler = ArrowController::$activeProject->getHandler(ArrowProject::IRemoteResponseHandler);
			$remoteResponseHAndler->setHeaders();
			$response = $remoteResponseHAndler->getResponse($instance->getError());
			ArrowController::end($response);	
		}	
		$controler->remoteResponse( $dataProviderBean );
	break;
	case ArrowRouter::TEMPLATE_CALL:
		
		if( count(ArrowRequestContext::getDefault()->getPost()) > 0)
			$controler->processToView();
		$pageClass = $router->getTemplate()->getPageClass();
		$pageClass->createPage();
		$pageClass->createView();
		$pageClass->controlsInit();
		$pageClass->afterControlsInit();
		$view = ArrowView::getCurrentView();
		echo $pageClass->display();
		
	break;	
	case ArrowRouter::CONTROLL_CALL:
		$pageClass = $router->getTemplate()->getPageClass();
		$pageClass->createPage();
		$pageClass->createView();
		$pageClass->controlsInit();
		$pageClass->afterControlsInit();
		echo $pageClass->generateControll();
	break;	
	case ArrowRouter::TEMPLATE_METHOD_CALL:
    $request = ArrowRequestContext::getDefault();
    $pageClass = $router->getTemplate()->getPageClass();
		$pageClass->createPage();
		$pageClass->createView();
		$pageClass->controlsInit();
		$pageClass->afterControlsInit();
		$method = $request->getRequest(ArrowRouter::TEMPLATE_METHOD_PARAMETER);
		
		$data = $request->getRequest( "methodCallData" ) ;
		$data = ( is_array($data) )? $data: array() ;
		$result = call_user_func_array  ( array( $pageClass, $method),  $data  );
  	$remoteResponseHAndler = ArrowController::$activeProject->getHandler(ArrowProject::IRemoteResponseHandler);
  	$response = $remoteResponseHAndler->getResponse($result);
		ArrowController::end($response);	

	break;
	
	
}


if( DEBUG_STATS && isset($_GET["dev"]) ) {
include( "./debug/DebugHelper.php" );

// ----------- WYDAJNOŚĆ SYSTEMU ------------------------------------
  $db_end_time = microtime(true);
  $db_sub = round( $db_end_time - $db_start_time, 6 ) ;
  $db_sql_time = round( ArrowOrmMysql::executionTime(), 6 ) ;
  $db_memory_end = number_format( memory_get_usage(1), 0, '.', ',' ) ;
  $db_memory_peak = number_format( memory_get_peak_usage(1), 0, '.', ',' ) ;
$db_print = <<<DB
 <div style="position:absolute;right:10px;top:35px;background-color:white;padding:20px;padding-top:10px;border:2px solid black;" onclick="this.style.display='none';" >
    <h2 style="text-align:center;" >DEBUG INFO</h2><br />
    <table class="clear" >
    <tr><td colspan="2" style="text-align:center;" >time [s]</td></tr>
    <tr><td>all script time:</td><td style="text-align:right;" ><b>$db_sub</b></td></tr>
    <tr><td>all mysql time:</td><td style="text-align:right;" ><b>$db_sql_time</b></td></tr>
    <tr><td colspan="2" style="text-align:center;" >memory [bytes]</td></tr>
    <tr><td>init</td><td style="text-align:right;" ><b>$db_memory_init</b></td></tr>
    <tr><td>after init</td><td style="text-align:right;" ><b>$db_memory_after_init</b></td></tr>
    <tr><td>end</td><td style="text-align:right;" ><b>$db_memory_end</b></td></tr>
    <tr><td>peek</td><td style="text-align:right;" ><b>$db_memory_peak</b></td></tr>
    <tr><td></td><td></td></tr>
    </table>
 </div>
DB;
  echo $db_print ;
  
// ----------------------- KONTROLKI -------------------------------  
$csroot = $view->getControlsRoot();
$tbody = "" ;
$stats = DebugHelper::getNodeStats( $csroot );
foreach( $stats as $k => $v ) 
	$tbody .= "<tr><td>$k</td><td>$v</td></tr>\n" ;

$db_control_print = <<<DB
 <div style="position:absolute;right:10px;top:305px;background-color:white;padding:20px;padding-top:20px;border:2px solid black;width:200px;" onclick="this.style.display='none';" >
    <h2 style="text-align:center;" >DEBUG CONTROLS INFO</h2><br />
    <table class="clear" >
    $tbody
    </table>
 </div>
DB;

echo $db_control_print ;

// ----------------------- ACCESS -----------------------------------
$accs = AccessManager::getConfigAccessSummary(false);
$accs = DebugHelper::printSetAccessForm( $accs );
$db_access_print = <<<DB
 <div style="position:absolute;right:10px;top:305px;background-color:white;padding:20px;padding-top:20px;border:2px solid black;height:400px;overflow:auto;"  >
 	<a href="#" onclick="this.parentNode.style.display='none';"  >zamknij</a>
    <h2 style="text-align:center;" >DEBUG ACCESS INFO</h2><br />
    $accs
 </div>
DB;

echo $db_access_print ;

// ------------------- strony ----------------------------------------

$page = $view->ts->get_template_vars("page") ;
if( is_object($page) ) {
$pinfo = $page->getPageInfo();
$pageinfo = "<table>" ;
foreach( $pinfo as $p ) {
	$pageinfo .= "<tr><td>{$p["place_id"]}</td><td>{$p["name"]}</td><td>{$p["type"]}</td><td>{$p["path"]}</td></tr>" ;
}

$pageinfo .= "</table>" ;

$db_page_print = <<<DB
 <div style="position:absolute;right:10px;top:305px;background-color:white;padding:20px;padding-top:20px;border:2px solid black;" onclick="this.style.display='none';" >
    <h2 style="text-align:center;" >DEBUG PAGE INFO</h2><br />
    <table class="clear" style="width:100%;" >
    	<tr><td>Id</td><td><b>{$page["id"]}</b></td></tr>
    	<tr><td>Name</td><td><b>{$page["name"]}</b></td></tr>
    	<tr><td>Rewrite_name</td><td><b>{$page["rewrite_name"]}</b></td></tr>
    	<tr><td>Language</td><td><b>{$page["language"]}</b></td></tr>
    	<tr><td>Active</td><td><b>{$page["active"]}</b></td></tr>
    	<tr><td>Sitemap</td><td><b>{$page["sitemap"]}</b></td></tr>
    	<tr><td>Show in menu</td><td><b>{$page["showinmenu"]}</b></td></tr>
    	<tr><td colspan="2" style="text-align:center;" ><b>Moduły</b></td></tr>
    	<tr><td colspan="2" >$pageinfo</td></tr>
    	<tr><td></td><td><b></b></td></tr>
    </table>
 </div>
DB;

echo $db_page_print ;
}
  
} 

ArrowController::end();
?>